import React, {Component} from 'react';
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import './dep.scss'

class Dep extends Component {
    render() {
        return (
            <div className="v-package">
                <div className="header-panel">
                    <div className="search">
                        <div className="input">
                            <i><FontAwesomeIcon icon="search"/></i><input
                            onKeyDown={(e) => {
                                if (e.keyCode === 13) this.search()
                            }} id={'searchInput'} type="text"/>
                            <div className="env" onClick={() => {
                                this.setState({dev: !this.state.dev})
                            }}>
                                <span>{this.state.dev ? 'D' : 'S'}</span></div>
                        </div>
                        <div onClick={() => this.search()} className="button">安装依赖</div>
                        <div className="button">私有组件</div>
                        <div className="button">检查更新</div>
                    </div>
                </div>
                <div className="main">
                    {["dep", "devDep"].map(j => {
                        return !this.state.pagResult.deps[j].obj.length ? (
                            <div className="loading" key={j}>稍等，正在载入...</div>
                        ) : (
                            <div className="dep" key={j}>
                                <div className="dep-tit">
                                    {j === "dep" ? "运行依赖 -S" : "开发依赖 -D"}
                                </div>
                                <div className="dep-list">
                                    {this.state.pagResult.deps[j].obj.map((e, index) => {
                                        return (
                                            <li className="item" key={index}>
                                                <div className="avatar"
                                                     style={{backgroundImage: "url('https://avatars.dicebear.com/v2/gridy/" + e.name.split("/")[0] + ".svg"}}/>
                                                <div className="info">
                                                    <h5 onClick={() => Dep.depDetail(e.name)}>{e.name}</h5>
                                                    <div className="sub-info">
                                                        <span>当前版本 <b>{e.version}</b> </span>
                                                        {e.last > e.version &&
                                                        <span className='new'
                                                              onClick={() => this.install(e.name, index, j, e.last)}>
                                                                最新版本 {e.last}
                                                            <i className={this.state.installStatus ? '' : 'act'}><FontAwesomeIcon
                                                                icon="upload"/></i>
                                                            </span>}
                                                    </div>
                                                </div>
                                                <div className="handle"><span
                                                    className={!this.state.uninstallStatus && this.state.uninstallIndex === index ? 'act' : ''}
                                                    onClick={() => this.uninstall(e.name, index, j)}><FontAwesomeIcon
                                                    icon="trash"/></span>
                                                </div>
                                            </li>
                                        );
                                    })}
                                </div>
                            </div>
                        );
                    })}
                </div>
            </div>
        );
    }

    constructor(props) {
        super(props);
        this.state = {
            serveRoot: [
                'http://localhost:2333/',
                'http://139.155.101.145:2333/',
                'http://10.11.165.86:3389/'
            ],
            serveIndex: 2,
            pagResult: {deps: {dep: {obj: []}, devDep: {obj: []}}, scripts: {}},
            package: {},
            installIndex: null,
            installStatus: true,
            uninstallIndex: null,
            uninstallStatus: true,
            searchState: 'searching',
            dev: false
        };
    }

    componentDidMount() {
        this.reqPag();
    }

    checkVersion(name) {
        // console.log(name)
        fetch(this.state.serveRoot[this.state.serveIndex] + 'check?name=' + name)
            .then(res => res.json())
            .then(data => {
                console.log(data)
            })
    }

    static depDetail(dep) {
        window.open("https://www.npmjs.com/package/" + encodeURIComponent(dep));
        console.log(dep);
    }

    reqPag() {
        fetch(this.state.serveRoot[this.state.serveIndex] + "package")
            .then(response => response.json())
            .then(data => {
                console.log(data);
                this.setState({
                    pagResult: data.result,
                    package: data.package
                });
            });
    }

    install(name, index, j, version) {
        if (!this.state.installStatus) return;
        let env = 'S';
        if (j.match('dev')) env = 'D';
        this.setState({
            installIndex: index,
            installStatus: false
        });
        fetch(this.state.serveRoot[this.state.serveIndex] + "install?module=" + name + '&env=' + env)
            .then(res => res.json())
            .then(data => {
                this.setState({
                    installIndex: null,
                    installStatus: true
                });
                console.log(data);
                this.updateItem(version, index, j)
            })
    }

    uninstall(name, index, j) {
        if (!this.state.uninstallStatus) return;
        this.setState({
            uninstallIndex: index,
            uninstallStatus: false
        });
        fetch(this.state.serveRoot[this.state.serveIndex] + "uninstall?module=" + name)
            .then(res => res.json())
            .then(data => {
                console.log(data);
                this.removeItem(index, j);
                this.setState({
                    uninstallStatus: true
                });
            })
    }

    search() {
        let value = document.querySelector('#searchInput').value;
        if (!value || !this.state.pagResult.deps.dep.obj.length) return;
        // console.log(value);
        if (!this.checkItem(value, this.state.dev)) {
            this.props.poopHandle(true, 'searchCheck');
            return;
        } else {
            this.setState({
                installStatus: false
            });
            this.props.poopHandle(true, 'searching');

        }
        fetch(this.state.serveRoot[this.state.serveIndex] + "search?module=" + value)
            .then(res => res.json())
            .then(res => {
                // console.log(res);
                if (res.err) {
                    this.props.poopHandle(true, 'searched');
                    this.setState({
                        installStatus: false
                    });
                    // console.log(res, res.err)
                } else {
                    console.log(res.data);
                    let version = res.data;
                    // let version = res.data.split('@\\u001b[32m')[1].split('\\u001b[39m\\u001b[22m')[0];
                    // console.log(version);
                    this.props.poopHandle(true, 'search');

                    let env = this.state.dev ? 'D' : 'S';
                    fetch(this.state.serveRoot[this.state.serveIndex] + "install?module=" + value + '&env=' + env)
                        .then(res => res.json())
                        .then(data => {
                            console.log(data);
                            this.props.poopHandle(true, 'searcher');
                            this.setState({
                                installStatus: false
                            });
                            setTimeout(() => {
                                this.props.poopHandle(false);
                            }, 1000);
                            this.addItem({
                                last: version,
                                name: value,
                                version: version
                            }, this.state.dev)
                        })
                }
            });
    }


    removeItem(index, env) {
        let result = this.state.pagResult;
        if (env.match('dev')) {
            result.deps.devDep.obj.splice(index, 1);
            result.deps.devDep.arr.splice(index, 1)
        } else {
            result.deps.dep.obj.splice(index, 1);
            result.deps.dep.arr.splice(index, 1);
        }
        this.setState({
            pagResult: result
        });
    }

    updateItem(item, index, env) {
        let result = this.state.pagResult;
        if (env.match('dev')) result.deps.devDep.obj[index].version = item;
        else result.deps.dep.obj[index].version = item;
        this.setState({
            pagResult: result
        })
    }

    addItem(item, env) {
        let result = this.state.pagResult;
        if (env) {
            result.deps.devDep.obj.push(item);
            result.deps.devDep.arr.push(item.name);
        } else {
            result.deps.dep.obj.push(item);
            result.deps.dep.arr.push(item.name);
        }
        this.setState({
            pagResult: result
        })
    }

    checkItem(item, env) {
        let list = this.state.pagResult.deps.dep.arr;
        if (env) list = this.state.pagResult.deps.devDep.arr;
        if (list.indexOf(item) > -1) return false;
        else return true
    }

}

export default Dep;